package com.hmall.order.tack;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;


import com.hmall.common.dto.client.ItemClient;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderService;
import com.hmall.order.service.IlogisticsService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;


import java.util.Date;
import java.util.List;
@Service
public class OrderTack {
    @Autowired
    ItemClient itemClient;
    @Autowired
    IOrderService orderService;
    @Autowired
    IOrderDetailService detailService;
    @GlobalTransactional
    @Scheduled(cron = "0 * * * * ?")
    public void cancel(){
        System.out.println("开始执行任务");
        //每一分钟运行一次定时任我
//        查找订单表未支付的记录
//        判断创建订单时间记录是否超过30分钟

//        获取当前时间往前推30分钟的时间
        Date time = new Date(System.currentTimeMillis() - 30 * 60 * 1000);
        LambdaQueryWrapper<Order> query = new LambdaQueryWrapper<>();
        query.eq(Order::getStatus,1);
        query.lt(Order::getCreateTime,time);
        List<Order> list = orderService.list(query);
        for (Order order : list) {
            order.setStatus(5);
            orderService.updateById(order);
            LambdaQueryWrapper<OrderDetail> queryDetail = new LambdaQueryWrapper<>();
            queryDetail.eq(OrderDetail::getOrderId,order.getId());
            List<OrderDetail> list1 = detailService.list(queryDetail);
            for (OrderDetail detail : list1) {
                itemClient.reduceStock(detail.getItemId(),-detail.getNum());
            }
        }
    }
}
